// pages/address/address.js
import {
  getMyAddress,
  getCommomAddress,
  addCommomAddress,
  deleteCommomAddress,
  getUserLogin
} from '../../apis/api'
import WxValidate from '../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModalStatus: false,
    showModalChangeStatus: false,
    city: false,
    region: ['', '', ''],
    customItem: '全部',
    addressList: [],
    currentId: 0,
    addressDTO: {
      addressRemark: '崇明味道太好吃啦',
      address: '',
      area: 'in',
      city: 'the',
      telephone: '',
      receiver: '',
      universalEnum: 'SAVE_UPDATE'
    },
    addressDTOC: {
      id: 0,
      addressRemark: '崇明味道太好吃啦',
      address: '',
      area: 'in',
      city: 'the',
      telephone: '',
      receiver: '',
      universalEnum: 'SAVE_UPDATE'
    },
    token: '',
    thisShow: false,
    isLog: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 渲染所有地址
  getLog: function () {
    if (!!!wx.getStorageSync('token')) wx.setStorageSync('token', 'token null')
    getUserLogin().then(async res => {
      console.log('yes', res);
      if (res.code === 200) {
        this.setData({
          isLog: res.data
        })
        if (this.data.token && this.data.isLog) {
          await this.getMyAllAddress()
        } else {
          wx.showModal({
            title: '提示',
            content: '获取用户地址功能需要登录，是否前往登录',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/tomeslog/tomeslog',
                })
              }
            }
          })
        }
      }
    })
  },
  onLoad: async function (options) {
    // this.setData({
    //   token: wx.getStorageSync('token'),
    // })
    // if(this.data.token){
    //   await this.getMyAllAddress()
    // } else {
    //   // wx.showModal({
    //   //   title: '提示',
    //   //   content: '获取用户地址功能需要登录，是否前往登录',
    //   //   success(res) {
    //   //     if(res.confirm) {
    //   //       wx.navigateTo({
    //   //         url: '/pages/tolog/tolog',
    //   //       })
    //   //     }
    //   //   }
    //   // })
    // } 
    this.initValidate()
  },
  // 省市区切换
  bindRegionChange: function (e) {
    this.setData({
      region: e.detail.value,
      city: true
    })
    wx.hideKeyboard()
  },
  // 新增地址弹窗
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  // 新增地址
  powerDrawerClick: async function (e) {
    // var currentStatu = e.currentTarget.dataset.statu;
    // const res = await addCommomAddress(this.data.addressDTO)
    // console.log(res);
    // await this.getMyAllAddress()
    // this.util(currentStatu)
  },
  util: function (currentStatu) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.opacity(0).rotateX(-100).step();
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      this.setData({
        animationData: animation
      })
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  // 修改地址弹窗
  powerDrawerChange: async function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    const id = e.currentTarget.dataset.addressid;
    const userId = e.currentTarget.dataset.userId;
    await this.getThisAddress(id, userId)
    this.setData({
      currentId: id
    })
    this.utilChange(currentStatu)
  },
  // 修改地址
  powerDrawerChangeClick: async function (e) {
    // var currentStatu = e.currentTarget.dataset.statu;
    // this.setData({
    //   ['addressDTOC.id']: this.data.currentId
    // })
    // const res = await getCommomAddress(this.data.addressDTOC)
    // this.getThisAddress()
    // await this.getMyAllAddress()
    // this.utilChange(currentStatu)
  },
  utilChange: function (currentStatu) {
    var animation = wx.createAnimation({
      timingFunction: "linear",
      delay: 0
    });
    this.animation = animation;
    animation.opacity(0).rotateX(-100).step();
    this.setData({
      animationDataChange: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      this.setData({
        animationDataChange: animation
      })
      if (currentStatu == "close") {
        this.setData({
          showModalChangeStatus: false
        });
      }
    }.bind(this), 200)
    if (currentStatu == "open") {
      this.setData({
        showModalChangeStatus: true
      });
    }
  },
  // 新增数据绑定
  bindUsernameChange: function (e) {
    this.setData({
      ['addressDTO.receiver']: e.detail.value
    })
  },
  bindTelephoneChange: function (e) {
    this.setData({
      ['addressDTO.telephone']: e.detail.value
    })
  },
  bindAddressChange: function (e) {
    const address = this.data.region.join('');
    this.setData({
      ['addressDTO.address']: address + e.detail.value
    })
  },
  // 修改数据绑定
  bindUsernameCChange: function (e) {
    this.setData({
      ['addressDTOC.receiver']: e.detail.value
    })
  },
  bindTelephoneCChange: function (e) {
    this.setData({
      ['addressDTOC.telephone']: e.detail.value
    })
  },
  bindAddressCChange: function (e) {
    this.setData({
      ['addressDTOC.address']: e.detail.value
    })
  },
  // 获取修改地址旧信息
  getThisAddress: async function (id, userId) {
    const res = await getMyAddress({
      id,
      userId
    })
    if (res.code === 200 && res.data) {
      this.setData({
        ['addressDTOC.address']: res.data[0].address,
        ['addressDTOC.telephone']: res.data[0].telephone,
        ['addressDTOC.receiver']: res.data[0].receiver
      })
    }
  },
  // 获取全部地址 
  getMyAllAddress: async function () {
    const userId = wx.getStorageSync('userId')
    const res = await getMyAddress({
      userId,
      isDelete: 0
    })
    console.log(res);
    if (!!res.data.length) {
      this.setData({
        addressList: res.data,
        thisShow: true
      })
    } else {
      this.setData({
        thisShow: false
      })
    }
  },
  // 删除地址
  deleteAddress: function (e) {
    const id = e.currentTarget.dataset.addressid;
    const _this = this
    wx.showModal({
      title: '提示',
      content: '此操作将删除改地址',
      success: async function (res) {
        if (res.confirm) {
          const res = await deleteCommomAddress({
            id
          })
          console.log(res);
          await _this.getMyAllAddress()
          if (res.code === 500 && res.msg.includes('默认')) {
            wx.showToast({
              title: '默认地址无法删除',
              icon: 'error'
            })
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.setData({
      token: wx.getStorageSync('token'),
    })
    this.getLog()
    this.initValidate()
  },

  // 校验
  showModal(err) {
    wx.showModal({
      content: err.msg,
      showCancel: false
    })
  },
  initValidate() {
    const rules = {
      aNickname: {
        required: true
      },
      aTelephone: {
        required: true,
        tel: true
      },
      aRegionone: {
        required: true
      },
      aRegiontwo: {
        required: true
      },
      aRegionthree: {
        required: true
      },
      aAddress: {
        required: true
      }
    }
    const messages = {
      aTelephone: {
        required: '请输入手机号',
        tel: '请输入正确的手机号'
      },
      aNickname: {
        required: '请输入收货人'
      },
      aRegionone: {
        required: '请选择省份'
      },
      aRegiontwo: {
        required: '请选择省份'
      },
      aRegionthree: {
        required: '请选择省份'
      },
      aAddress: {
        required: '请输入地址'
      }
    }
    const rulesChange = {
      bNickname: {
        required: true
      },
      bTelephone: {
        required: true,
        tel: true
      },
      bAddress: {
        required: true
      }
    }
    const messageChange = {
      bAddress: {
        required: '请输入地址'
      },
      bNickname: {
        required: '请输入收货人'
      },
      bTelephone: {
        required: '请输入手机号',
        tel: '请输入正确的手机号'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
    this.WxValidate1 = new WxValidate(rulesChange, messageChange)
  },
  formSubmit: async function (e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    var currentStatu = e.detail.target.dataset.statu;
    await addCommomAddress(this.data.addressDTO)
    await this.getMyAllAddress()
    this.util(currentStatu)
  },
  formSubmitChange: async function (e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate1.checkForm(params)) {
      const error = this.WxValidate1.errorList[0]
      this.showModal(error)
      return false
    }
    var currentStatu = e.detail.target.dataset.statu;
    this.setData({
      ['addressDTOC.id']: this.data.currentId
    })
    await getCommomAddress(this.data.addressDTOC)
    this.getThisAddress()
    await this.getMyAllAddress()
    this.utilChange(currentStatu)
  }
})